package cn.wolfcode.crm.shiro;

import cn.wolfcode.crm.util.JsonResult;
import com.alibaba.fastjson.JSON;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
import org.springframework.stereotype.Component;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

@Component("crmFormAuthenticationFilter")
public class CRMFormAuthenticationFilter extends FormAuthenticationFilter {

    @Override
    protected boolean onLoginFailure(AuthenticationToken token, AuthenticationException e, ServletRequest request, ServletResponse response) {
        //登录失败 将错误信息封装到JsResult 对象中 然后转成 json字符串  响应给页面

        String msg = "";
        if(e instanceof UnknownAccountException)
        {
            msg="账号错误";
        }else if (e instanceof IncorrectCredentialsException){
            msg="密码错误";
        }else {
            msg = "未知错误";
        }
        e.printStackTrace();
        response.setContentType("text/json;charset=UTF-8");

        try {
            JsonResult result = new JsonResult();
            result.mark(msg);
            response.getWriter().print(JSON.toJSONString(result));
        }catch (Exception e1){
            e1.printStackTrace();
        }
        return false;
    }

    @Override
    protected boolean onLoginSuccess(AuthenticationToken token, Subject subject, ServletRequest request, ServletResponse response) throws Exception {
        //登录成功  将信息封装到JsResult 对象中 然后转成 json字符串  响应给页面
        response.setContentType("text/json;charset=UTF-8");
        JsonResult result = new JsonResult();
        response.getWriter().println(JSON.toJSONString(result));
        return false;
    }
}
